﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Security;
using System.Security.Permissions;

namespace Learn.SharePoint.com
{
    public class LastViewedField : SPFieldText
    {
        public LastViewedField(SPFieldCollection fields, string fieldName)
            : base(fields, fieldName)
        {
            ReadOnlyField = true;
        }
        public LastViewedField(SPFieldCollection fields, string typeName, string displayName)
            : base(fields, typeName, displayName) { }

        public override Type FieldValueType
        {
            get
            {
                return typeof(LastViewedFieldValue);
            }
        }

        public override string GetFieldValueAsText(object value)
        {
            string returnValue = "";
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (var site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (var web = site.AllWebs[SPContext.Current.Web.ID])
                    {
                        web.AllowUnsafeUpdates = true;
                        var list = web.Lists[this.ParentList.ID];
                        if (value != null)
                        {                            
                            var occurredOrNeverAndIdValue = value.ToString().Split(',');
                            var occurredOrNeverValue = occurredOrNeverAndIdValue[0];
                            var itemId = int.Parse(occurredOrNeverAndIdValue[1]);
                            var item = list.GetItemById(itemId);
                            var query = new SPAuditQuery(SPContext.Current.Site);
                            query.RestrictToListItem(item);
                            query.AddEventRestriction(SPAuditEventType.View);
                            var entries = this.ParentList.Audit.GetEntries(query);
                            if (entries.Count > 0)
                            {
                                returnValue = TimeZoneInfo.ConvertTimeFromUtc(entries[entries.Count - 1].Occurred, TimeZoneInfo.Local).ToString();
                                if (TimeZoneInfo.ConvertTimeFromUtc(entries[entries.Count - 1].Occurred, TimeZoneInfo.Local).ToString() + "," + itemId.ToString() != value.ToString())
                                {
                                    item[Id] = TimeZoneInfo.ConvertTimeFromUtc(entries[entries.Count - 1].Occurred, TimeZoneInfo.Local).ToString() + "," + itemId.ToString();
                                    item.SystemUpdate(false);
                                }
                            }
                            else
                            {
                                returnValue = "Never";
                                if ("Never," + itemId.ToString() != value.ToString())
                                {
                                    item[Id] = "Never," + itemId.ToString();
                                    item.SystemUpdate(false);
                                }
                            }                            
                        }
                        else
                        {
                            returnValue = base.GetFieldValueAsText(value);
                        }
                        web.AllowUnsafeUpdates = false;
                    }
                }
            });
            return returnValue;
        }

        public override BaseFieldControl FieldRenderingControl
        {
            [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
            get
            {
                BaseFieldControl fieldControl = new LastViewedFieldControl();
                fieldControl.FieldName = this.InternalName;
                return fieldControl;
            }
        }
    }
}
